package com.bdqn.qnnews.aliyungreen.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.bdqn.qnnews.aliyungreen.config.AliYunGreenProperties;
import com.bdqn.qnnews.aliyungreen.pojo.GreenScanResult;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author xlzhang
 * @date 2024/1/2 13:55
 */
@Slf4j
public class AliYunGreenUtil {

    private final Client client;
    private final AliYunGreenProperties prop;

    public AliYunGreenUtil(Client client, AliYunGreenProperties prop) {
        this.client = client;
        this.prop = prop;
    }

    /**
     * 文本内容审核方法
     * @param content 要审核的文本内容
     * @return
     */
    public GreenScanResult greenText( String content){
        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        // 参数构造器
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("dataId", UUID.randomUUID().toString());
        serviceParameters.put("content", content);

        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
            throw new RuntimeException("审核内容不能为空");
        }

        // 封装检查请求对象
        TextModerationRequest textModerationRequest = new TextModerationRequest()
                .setService(prop.getTextService())
                .setServiceParameters(serviceParameters.toJSONString());

        try {
            final TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);

            // 解析审核响应结果
            final GreenScanResult greenScanResult = new GreenScanResult();
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
                    log.debug("内容审核响应数据:{}",result);
                    greenScanResult.setCode(result.code);
                    greenScanResult.setRequestId(result.getRequestId());
                    greenScanResult.setMessage(result.getMessage());
                    Integer code = result.getCode();
                    if (code != null && code == 200) {
                        TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
                        final GreenScanResult.LabelInfo labelInfo = new GreenScanResult.LabelInfo();
                        // 获取标签数据
                        labelInfo.setLabels(data.getLabels());
                        // 简析并获取审核反馈的异常关键字内容
                        final JSONObject jsonObject = JSON.parseObject(data.getReason());
                        if (jsonObject != null){
                            final String riskWords = jsonObject.getString("riskWords");
                            labelInfo.setReason(riskWords);
                        }
                        greenScanResult.setData(labelInfo);
                    } else {
                        log.error("文本审核不成功,code:{}  ,message:{}",code,result.getMessage());
                    }
                    return greenScanResult;
                } else {
                    throw new RuntimeException("响应异常. status:" + response.getStatusCode());
                }
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 图片类容审核
     * @param imageUrl 要审核的图片地址（必须是外部能够直接访问的图片地址）
     * @return
     */
    public Map<String,Object> greenImageScan(String imageUrl) {

        //检测参数构造
        Map<String, String> serviceParameters = new HashMap<>();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", imageUrl);
        serviceParameters.put("dataId", UUID.randomUUID().toString());

        ImageModerationRequest request = new ImageModerationRequest();
        //图片检测service: baselineCheck 通用基线检测。
        request.setService(prop.getImgService());
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        try {
            // 调用方法获取检测结果。
            ImageModerationResponse response = client.imageModerationWithOptions(request, runtime);
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageModerationResponseBody body = response.getBody();
                    return JSON.parseObject(JSON.toJSONString(body), Map.class);
                } else {
                    throw new RuntimeException("响应异常. status:" + response.getStatusCode());
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
